import React from 'react';
import { Modal, Form, Input, message } from 'antd';

import SparkChannel from '../ipc/sparkchannel'

class ReportDirDialog extends React.Component {
  constructor(props) {
    super(props);

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleAfterClose = this.handleAfterClose.bind(this);

    this.formRef = React.createRef();
    this.state = { confirmLoading: false }
  }

  async handleSubmit() {
    try {
      const values = await this.formRef.current.validateFields();

      this.onFinish(values);
    } catch (err) {
      console.log('validateFields error', err);
    }
  }
  handleAfterClose() {
    this.formRef.current.resetFields();
  }

  async onFinish(values) {
    const dirname = values.dirname;

    this.setState({ confirmLoading: true });
    if (this.props.edit) {
      const directory = this.props.directory;
      try {
        const channel = await SparkChannel();
        let resp = await channel.request_update_directory({
          id: directory.id,
          directory_name: dirname,
        });
        console.log('update dir result', resp);
        this.props.onDirSaved(this.props.edit, resp);
      } catch (err) {
        console.log('update report dir fail', err)
        message.error('修改目录失败');
      }
    } else {
      try {
        const channel = await SparkChannel();
        let resp = await channel.request_insert_directory({ directory_name: dirname });
        console.log('create dir result', resp);
        this.props.onDirSaved(this.props.edit, resp);
      } catch (err) {
        console.log('create report dir fail', err)
        message.error('创建目录失败');
      }
    }
    this.setState({ confirmLoading: false });
  }


  render() {
    const { edit, open, onCancel } = this.props;
    const initialValues = {};
    if (edit) {
      initialValues.dirname = this.props.directory.directory_name;
    }

    return (
      <Modal title={edit ? "编辑目录" : "新建目录"}
        zIndex={1020}
        open={open}
        confirmLoading={this.state.confirmLoading}
        onCancel={onCancel}
        onOk={this.handleSubmit}
        afterClose={this.handleAfterClose}>
        <Form
          ref={this.formRef}
          colon={false}
          initialValues={initialValues}>
          <Form.Item
            label="目录名称"
            name="dirname"
            rules={[
              {
                required: true,
                message: '请输入目录名称!',
              },
            ]}
          >
            <Input type="text" />
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}

export default ReportDirDialog